package model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import exceptions.InvalidDataException;

public class ConnectionSettings {
	private String dbAdress;
	private String dbPort;
	private String dbLogin;
	private String dbPass;
	
	/**
	 * @param dbAdress
	 * @param dbPort
	 * @param dbLogin
	 * @param dbPass
	 * @throws InvalidDataException 
	 */
	public ConnectionSettings(String dbAdress, String dbPort, String dbLogin, String dbPass) throws InvalidDataException {
		super();
		this.setDbAdress(dbAdress);
		this.setDbPort(dbPort);
		this.setDbLogin(dbLogin);
		this.setDbPass(dbPass);
	}
	/**
	 * @return the dbAdress
	 */
	public String getDbAdress() {
		return dbAdress;
	}
	/**
	 * @param dbAdress the dbAdress to set
	 * @throws InvalidDataException 
	 */
	public void setDbAdress(String dbAdress) throws InvalidDataException {
		if(!this.validIP(dbAdress)) throw new InvalidDataException();
		this.dbAdress = dbAdress.toLowerCase().trim();
	}
	/**
	 * @return the dbPort
	 */
	public String getDbPort() {
		return dbPort;
	}
	/**
	 * @param dbPort the dbPort to set
	 * @throws InvalidDataException 
	 */
	public void setDbPort(String dbPort) throws InvalidDataException {
		if(!this.validPort(dbPort)) throw new InvalidDataException();
		this.dbPort = dbPort.toLowerCase().trim();
	}
	/**
	 * @return the dbLogin
	 */
	public String getDbLogin() {
		return dbLogin;
	}
	/**
	 * @param dbLogin the dbLogin to set
	 * @throws InvalidDataException 
	 */
	public void setDbLogin(String dbLogin) throws InvalidDataException {
		if(dbLogin == null || dbLogin.isEmpty()) throw new InvalidDataException();
		this.dbLogin = dbLogin.toLowerCase().trim();
	}
	/**
	 * @return the dbPass
	 */
	public String getDbPass() {
		return dbPass;
	}
	/**
	 * @param dbPass the dbPass to set
	 * @throws InvalidDataException 
	 */
	public void setDbPass(String dbPass) throws InvalidDataException {
		if(dbPass == null || dbPass.isEmpty()) throw new InvalidDataException();
		this.dbPass = dbPass.toLowerCase().trim();
	}
	/**
	 * @param ip
	 * @return true if IP is valid
	 */
	public boolean validIP(String ip) {
	    if (ip == null || ip.isEmpty()) return false;
	    ip = ip.trim();
	    if ((ip.length() < 6) & (ip.length() > 15)) return false;

	    try {
	        Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
	        Matcher matcher = pattern.matcher(ip);
	        return matcher.matches();
	    } catch (PatternSyntaxException ex) {
	        return false;
	    }
	}
	
	public boolean validPort(String port){
		if(port == null || port.isEmpty()) return false;
		port = port.trim();
		int portToInt = Integer.parseInt(port);
		
		if(portToInt < 1 || portToInt > 65536) return false;
		else return true;
	}
	

}
